/**
 * @description: 文件描述
 * @version: 0.0.1
 * @author: xxx
 * @Date: 2025-01-08 10:28:44
 */
let { trackMoreFun, globalData } = getApp();
Component({
  data: {
    valList: ['-5', '-4', '-3', '-2', '-1', '0', '+1', '+2', '+3', '+4', '+5'],
    selectedItems: [],
    maxSelect: 3,
    setY: 380, // 初始位置调整为380（760/2）
    startY: 0, // 记录触摸起始位置 
    typeVal: 0, //气息类型
    xclskus: [],
    imgHeight: 760,
    moveLineHeight: 12,
    tickSpacing: 0,
    mouseOption: [],
    scaleSkuArr: [
      ['P122120', 'P122150', 'P101560', 'P122080', 'P122100'],
      ['P122100', 'P122110', 'P122120', 'P122130', 'P122020', 'P122010', 'P122160', 'P122490'],
      ['P122110', 'P122120', 'P122130', 'P122020', 'P122010', 'P122160', 'P122490'],
      ['P122140', 'P122050', 'P122130', 'P122090', 'P122060', 'P122070', 'P122030', 'P122160'],
      ['P122050', 'P122150', 'P122090', 'P122040', 'P122030', 'P122180']
    ],
    xclskus_sort: [],
    scaleVal: '0',
    scaleNum: 1,
    area1Height: 0,
  },
  async didMount() {
    globalData.pageNum = 3
    trackMoreFun('预览_发现你的嗅觉个性_选择气息类型页面','into' )
    this.setData({
      scaleNum: Number(this.calcH())
    })


    // 计算不同屏幕下 moveLine的高度
    const moveLineHeight = this.setPosition(12)
    const imgHeight = this.setPosition(760)

    // 计算每个刻度的间距
    const tickSpacing = (imgHeight - moveLineHeight) / (this.data.valList.length - 1);
    const mouseOption = []
    // 计算每个刻度的位置
    for (let i = 0; i < 11; i++) {
      mouseOption.push({
        val: i + 0.3,
        mouseVal: Number(((tickSpacing * i)).toFixed(3)),
        num: i
      })
    }
    // globalData.typeData.num=mouseOption
    const num = globalData.typeData.num
    console.log(mouseOption, num, 'asdascascscasc')
    const data = mouseOption.find(item => item.mouseVal == mouseOption[num].mouseVal)
    this.setData({
      moveLineHeight,
      imgHeight,
      tickSpacing,
      mouseOption,
      setY: mouseOption[num].mouseVal,
      typeVal: data.val
    })

    const xclskusArr = await this.getStorage('xclskusArr')

    this.setData({
      xclskus: xclskusArr,

    })
  },
  methods: {
    calcH() {
      const systemInfo = my.getSystemInfoSync();
      const bottomH = 418 //设计底部区域高度
      const areaH_ = 1030//设计稿文字区域高度
      // // 获取屏幕宽度和高度（单位：px）
      const screenWidth = systemInfo.screenWidth; // 屏幕宽度
      let screenHeight = systemInfo.screenHeight - systemInfo.statusBarHeight - systemInfo.titleBarHeight; // 屏幕高度
      // 将屏幕高度转换为 rpx
      let rem_ = screenWidth / 750
      let screen_h = screenHeight / rem_  //不同屏幕设备高度
      const content_h = screen_h - bottomH //不同设备 内容的高度
      let scaleNum = (content_h / areaH_).toFixed(3)
      scaleNum = (1 - scaleNum) <= 0.03 ? 1 : scaleNum
      if (scaleNum > 1) {
        scaleNum = 1
      }
      this.setData({
        area1Height: content_h
      })
      return scaleNum
    },
    async changeNextTo() {
      trackMoreFun(`点击_发现你的嗅觉个性_点击完成_${this.data.scaleVal}`, 'click')
      try {
        const selectArr = await this.getStorage('selectArr')
        selectArr[2] = this.data.typeVal
        this._countScore(selectArr)
        console.log(selectArr, 'selectArrselectArrselectArrselectArrselectArrselectArr')
        my.setStorage({
          key: 'xclskusArr_sort',
          data: this.data.xclskus_sort
        })
        this.props.onMyEvent({ num: 4 });
      } catch (error) {
        console.log(error, 'changeNextTo')
      }
    },
    // 开始拖拽
    handleTouchStart(e) {
      this.setData({
        startY: e.touches[0].clientY
      });
    },
    // 拖拽中
    handleTouchMove(e) {
      const touch = e.touches[0];
      const deltaY = touch.clientY - this.data.startY;
      // const sensitivity = 1.5; // 增加灵敏度 * sensitivity;
      const newY = this.data.setY + deltaY
      // 限制在0到760之间
      const clampedY = Math.max(0, Math.min((this.data.imgHeight - this.data.moveLineHeight), newY));



      this.setData({
        setY: clampedY,
        startY: touch.clientY
      });

    },
    // 结束拖拽
    handleTouchEnd() {
      try {
        // 计算最近的刻度位置
        const nearestTick = Number((Math.round(this.data.setY / this.data.tickSpacing) * this.data.tickSpacing).toFixed(3))
        const data = this.data.mouseOption.find(item => item.mouseVal == nearestTick)
        this.setData({
          setY: nearestTick,
          typeVal: data.val
        });

        const scaleOption = [
          { val: 0.3, scaleVal: -5, num: 0 },
          { val: 1.3, scaleVal: -4, num: 1 },
          { val: 2.3, scaleVal: -3, num: 2 },
          { val: 3.3, scaleVal: -2, num: 3 },
          { val: 4.3, scaleVal: -1, num: 4 },
          { val: 5.3, scaleVal: 0, num: 5 },
          { val: 6.3, scaleVal: 1, num: 6 },
          { val: 7.3, scaleVal: 2, num: 7 },
          { val: 8.3, scaleVal: 3, num: 8 },
          { val: 9.3, scaleVal: 4, num: 9 },
          { val: 10.3, scaleVal: 5, num: 10 },
        ]
        const scaleVal = scaleOption.find(i => i.val == data.val).scaleVal
        globalData.typeData.num = data.num
        trackMoreFun(`点击_发现你的嗅觉个性_选择气息类型_${scaleVal}`, 'click')
        this.setData({
          scaleVal
        })
      } catch (error) {
        console.log(error, 'handleTouchEnd')
      }
    },
    setPosition(y) {
      const systemInfo = my.getSystemInfoSync();
      // 判断设备类型
      if (systemInfo.platform === 'iOS') {
        const screenWidth = systemInfo.screenWidth
        return (y * screenWidth) / 750
      } else if (systemInfo.platform === 'Android') {
        const screenWidth = systemInfo.screenWidth; // 屏幕宽度（px）
        const pixelRatio = systemInfo.pixelRatio; // 设备像素比
        const actualY = (y * screenWidth) / 750 / pixelRatio;
        return actualY
      } else {
        const screenWidth = systemInfo.screenWidth; // 屏幕宽度（px）
        const pixelRatio = systemInfo.pixelRatio; // 设备像素比
        const actualY = (y * screenWidth) / 750 / pixelRatio;
        return actualY
      }

    },

    changeBack() {
      trackMoreFun('点击_发现你的嗅觉个性_点击上一步', 'click')
      this.props.onMyEvent({ num: 2 });
    },
    getStorage(key) {
      return new Promise((resolve, reject) => {
        my.getStorage({
          key: key,
          success: function (res) {
            resolve(res.data)
          },
          fail: function (res) {
            reject([])
          }
        });
      })
    },
    async onShow() {

    },
    async onLoad(query) {


    },
    _countScore(currentSelectArr) {
      try {
        const xclskus = this.data.xclskus
        let _this = this;
        // 统计第一步得分
        currentSelectArr[0].forEach(function (item) {
          _this._changeXclskuScore(item, 1);
        });

        // 统计第二步得分
        currentSelectArr[1].forEach((skuListItem) => {
          skuListItem.forEach((item) => {
            _this._changeXclskuScore(item, 2);
          });
        });

        console.log(currentSelectArr, 'currentSelectArr', this.data.xclskus)
        let selectedRange = currentSelectArr[2];
        let scaleSkuArr = this.data.scaleSkuArr;
        if (selectedRange <= 2) {
          scaleSkuArr[0].forEach((item, i) => {
            let xclArrItem = xclskus.filter(xclskus => xclskus.sku === item);
            if (!!xclArrItem[0]) {
              xclArrItem[0].score += 2;
            }
          });
        }
        if (2 < selectedRange && selectedRange <= 4) {
          scaleSkuArr[1].forEach((item, i) => {
            let xclArrItem = xclskus.filter(xclskus => xclskus.sku === item);
            if (!!xclArrItem[0]) {
              xclArrItem[0].score += 2;
            }
          });
        }
        if (4 < selectedRange && selectedRange <= 6) {
          scaleSkuArr[2].forEach((item, i) => {
            let xclArrItem = xclskus.filter(xclskus => xclskus.sku === item);
            if (!!xclArrItem[0]) {
              xclArrItem[0].score += 2;
            }
          });
        }
        if (6 < selectedRange && selectedRange <= 8) {
          scaleSkuArr[3].forEach((item, i) => {
            let xclArrItem = xclskus.filter(xclskus => xclskus.sku === item);
            if (!!xclArrItem[0]) {
              xclArrItem[0].score += 2;
            }
          });
        }
        if (selectedRange > 8) {
          scaleSkuArr[4].forEach((item, i) => {
            let xclArrItem = xclskus.filter(xclskus => xclskus.sku === item);
            if (!!xclArrItem[0]) {
              xclArrItem[0].score += 2;
            }
          });
        }

        const xclskus_sort = this.data.xclskus
        xclskus_sort.sort((a, b) => b.score - a.score)
        this.setData({
          scaleSkuArr,
          xclskus_sort
        })
      } catch (error) {
        console.log(error, 'llllllllll')
      }
    },
    _changeXclskuScore(spu, score) {
      const xclskus = this.data.xclskus
      xclskus.forEach((item) => {
        if (spu == item.sku) {
          item.score += score;
        }
      });
    },
  }

})
